import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_play_time_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_select_terminal_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_view_model.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/terminal_by_pic_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/delegate/watermark_text_video_delegate.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:transformer_page_view/transformer_page_view.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import 'change_to_diy_page_event.dart';

///视频、图片设置参数页面
class PosterPushSettingsPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "PosterPushSettingsPage";

  static const String INDEX_TOP_INFO_API =ServerApi.BASE_URL + "app/appTerminalManageHome";
  final String picid;
  final String picurl;
  final String id;
  const PosterPushSettingsPage({Key key, this.picid, this.picurl, this.id}):super(key: key);

  @override
  _PosterPushSettingsPageState createState() => _PosterPushSettingsPageState();

  ///跳转方法
  static Future<bool> navigatorPush(
      BuildContext context, String picid, String picurl, String id) {
    return RouterUtils.routeForFutureResult(
      context,
      PosterPushSettingsPage(
        picid: picid,
        picurl: picurl,
        id: id,
      ),
      routeName: PosterPushSettingsPage.ROUTER,
    );
  }
}

class _PosterPushSettingsPageState extends BaseState<PosterPushSettingsPage>{

  String _hsns = "";
  String _selectHsns = "";
  String _noHaveHsns = "";
  int _allTerminalSize = 0;
  String startDayStr = "";
  String endDayStr = "";
  DateTime startDay;
  DateTime endDay;
  String playTime = "";
  String interval = "";
  NewTerminalListViewModel _viewModel;
  ValueNotifier<int> _pageValueNotifier;
  TransformerPageController _pageController;
  Key _pageViewKey = UniqueKey();
  static const int LIMIT_LOOP_COUNT = 2000;
  StreamSubscription _terminalNumRefreshSubscription;
  ScrollController _controller;
  double _scale = 1.0;
  AiPosterIndexViewModel _aiPosterIndexViewModel;
  @override
  void initState() {
    super.initState();
    _controller= ScrollController();
    _viewModel = NewTerminalListViewModel(this);
    _aiPosterIndexViewModel = AiPosterIndexViewModel(this);

    startDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
    startDayStr = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);
    endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
        + 14*24*3600*1000);
    endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
    playTime = DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":"");
    playTime += " ~ ";
    playTime += DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(endDay.millisecondsSinceEpoch)?"(今天)":"");
    interval = "15天";
    String cacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              bean.data.bindTerminalList.forEach((element) {
                if (!_hsns.contains(element.hsn)) {
                  _hsns += element.hsn;
                  _hsns += ",";
                }
              });
              _allTerminalSize = bean.data.bindTerminalList.length;
            }
          }
          if(StringUtils.isNotEmpty(_hsns) && _hsns.endsWith(",")){
            _hsns = _hsns.substring(0, _hsns.length-1);
          }
        });
      }
    });
    _viewModel.getTerminalListByPic(context, widget?.picid, _hsns);
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        _allTerminalSize = event?.num??0;
      }
    });
    _pageValueNotifier = ValueNotifier(_getInitPosition());
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    super.dispose();
  }

  @override
  void didUpdateWidget(PosterPushSettingsPage oldWidget) {

    Future.delayed(Duration(microseconds: 0), () {
      _pageViewKey = UniqueKey();

      _pageController = TransformerPageController(
        keepPage: true,
        initialPage: _getInitPosition(),
        loop: false,
      );
      _pageValueNotifier?.value = _getInitPosition();
      setState(() {});
    });

    super.didUpdateWidget(oldWidget);

  }

  @override
  Widget build(BuildContext context) {
    _scale = ScreenUtils.screenW(context)/375;
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: Column(
        children: <Widget>[
          _toTopBarWidget(),
          _toPlaceHolderWidget(),
        ],
      ),
    );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getTerminalListByPic(context, widget?.picid, _hsns),
            loadingOnClick: () => _viewModel
                .getTerminalListByPic(context, widget?.picid, _hsns),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return WillPopScope(
      child: VgTopBarWidget(
        isShowBack: true,
        title:"播放文件·1",
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      ),
    );
  }

  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalByPicValueNotifier,
        builder: (BuildContext context, TerminalByPicDataBean detailBean, Widget child){
          if(detailBean?.usehsnList != null && (detailBean?.usehsnList?.length??0) > 0){
            if(StringUtils.isNotEmpty(_hsns) && !_hsns.endsWith(",")){
              _hsns += ",";
            }
            detailBean.usehsnList.forEach((element) {
              if(!_hsns.contains(element?.hsn)){
                _hsns += element?.hsn;
                _hsns += ",";
              }
            });
            if(StringUtils.isNotEmpty(_hsns) && _hsns.endsWith(",")){
              _hsns = _hsns.substring(0, _hsns.length-1);
            }
            if(StringUtils.isNotEmpty(_selectHsns)){
              _hsns = _selectHsns;
            }
          }
          return Column(
            children: <Widget>[
              _showImageListWidget(),
              _settingsWidget(),
              SizedBox(height: 30,),
              _toConfirmWidget(),
            ],
          );
        }
    );
  }

  ///横向图片展示栏
  Widget _showImageListWidget(){
    double imageHeight = 251 *_scale;
    return Container(
      padding: EdgeInsets.only(top: 20, bottom: 17),
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      ),
      child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap:(){
            VgPhotoPreview.single(context, widget?.picurl);
          },
          child: _toSingleImageWidget(imageHeight)
      ),
    );
  }

  Widget _toSingleImageWidget(double imageHeight){
    VgCacheNetWorkImage image;
    image = VgCacheNetWorkImage(
        widget?.picurl ?? "",
        imageQualityType: ImageQualityType.high,
        fit: BoxFit.cover,
        placeWidget: Container(color: Colors.black,)
    );
    return Container(
      height: imageHeight,
      alignment: Alignment.center,
      child: image,
    );
  }



  ///初始化位置
  int _getInitPosition() {
    int initIndex = 0;
    return (1 * LIMIT_LOOP_COUNT / 2).floor() + initIndex;
  }

  ///播放终端、播放天数
  Widget _settingsWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        children: <Widget>[
          _playTerminalWidget(),
          _playTimes(),
        ],
      ),
    );
  }



  ///播放终端
  Widget _playTerminalWidget(){
    String terminalHint = "";
    int selectedSize = StringUtils.isEmpty(_hsns)?0:_hsns.split(",").length;
    if(_allTerminalSize != 0){
      if(selectedSize == _allTerminalSize){
        terminalHint = "全部$selectedSize台终端";
      }else if(selectedSize == 0){
        terminalHint = "暂不选择终端";
      }else{
        terminalHint = "$selectedSize台终端";
      }
    }

    return Visibility(
      visible: (_allTerminalSize != 0),
      child: Column(
        children: [
          GestureDetector(
            onTap: () async{
              String hsns = await MediaSelectTerminalPage.navigatorPush(context,
                  hsns: _hsns, forceSelect: true);
              if(hsns != null){
                setState(() {_hsns = hsns;});
              }
            },
            child: Container(
              height: 50,
              padding: EdgeInsets.symmetric(horizontal: 15),
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              child: Row(
                children: <Widget>[
                  Text(
                    "播放终端",
                    style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                    ),
                  ),
                  Spacer(),
                  Row(
                    children: <Widget>[
                      Text(
                        terminalHint,
                        style: TextStyle(
                          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                          fontSize: 14,
                          height: 1.2,
                        ),
                      ),
                      SizedBox(width: 9,),
                      Image.asset(
                        "images/index_arrow_ico.png",
                        width: 6,
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          Visibility(
              visible: selectedSize != 0,
              child: _toSplitLineWidget()
          ),
        ],
      ),
    );
  }

  ///播放天数
  Widget _playTimes(){
    int selectedSize = StringUtils.isEmpty(_hsns)?0:_hsns.split(",").length;
    return Visibility(
      visible: selectedSize != 0,
      child: Column(
        children: [
          GestureDetector(
            onTap: () async{
              Map<String, dynamic> resultMap = await MediaPlayTimePage.navigatorPush(context, startDay: startDay, endDay: endDay);
              if(resultMap == null){
                return;
              }
              setState(() {
                startDayStr = resultMap[MediaPlayTimePage.RESULT_START_DAY_STR];
                endDayStr = resultMap[MediaPlayTimePage.RESULT_END_DAY_STR];
                startDay = resultMap[MediaPlayTimePage.RESULT_START_DAY];
                endDay = resultMap[MediaPlayTimePage.RESULT_END_DAY];

                playTime = DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":"");
                if(endDay == null){
                  playTime += " ~ ";
                  playTime += "永久";
                  interval = "永久";
                }else if(startDayStr != endDayStr){
                  playTime += " ~ ";
                  playTime += DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "");
                  interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
                }else {
                  interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
                }

                print(PosterPushSettingsPage.ROUTER + ":" + startDayStr);
                print(PosterPushSettingsPage.ROUTER + ":" + endDayStr);
              });
            },
            child: Container(
              height: 64,
              padding: EdgeInsets.symmetric(horizontal: 15),
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: [
                      Text(
                        "播放天数",
                        style: TextStyle(
                          fontSize: 14,
                          height: 1.2,
                          color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                        ),
                      ),
                      Spacer(),
                      Row(
                        children: <Widget>[
                          Text(
                            interval,
                            style: TextStyle(
                              color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                              fontSize: 14,
                              height: 1.2,
                            ),
                          ),
                          SizedBox(width: 9,),
                          Image.asset(
                            "images/index_arrow_ico.png",
                            width: 6,
                          )
                        ],
                      ),

                    ],
                  ),
                  Text(
                    playTime,
                    style: TextStyle(
                      fontSize: 11,
                      height: 1.2,
                      color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    ),
                  ),
                ],
              ),
            ),
          ),
          // SizedBox(height: 14,)
        ],
      ),
    );
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      height: 0.5,
      margin: const EdgeInsets.only(left: 15, right: 0),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  ///确定
  Widget _toConfirmWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      height: 40,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      unSelectBgColor: Color(0xFF3A3F50),
      selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
        color: VgColors.INPUT_BG_COLOR,
        fontSize: 15,
      ),
      selectedTextStyle: TextStyle(
        color: Colors.white,
        fontSize: 15,
        // fontWeight: FontWeight.w600
      ),
      text: "确定",
      onTap: (){
        _doConfirm();
      },
    );
  }



  _doConfirm(){
    //是否需要跳转到待播列表
    //如果当前传的数据开始日期在当前日期之后就需要跳转
    bool needPopToWait = false;
    DateTime currentDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
    if(currentDay.millisecondsSinceEpoch < (startDay?.millisecondsSinceEpoch??0)){
      needPopToWait = true;
    }
    String tempHsns = _hsns;
    if(StringUtils.isNotEmpty(_noHaveHsns)){
      tempHsns = tempHsns + "," + _noHaveHsns;
    }
    _aiPosterIndexViewModel.pushDiyPic(context, endDayStr, tempHsns,
        widget?.picid, widget?.picurl, startDayStr, widget?.id, (){
          VgEventBus.global.send(new ChangeToDiyPageEvent());
            RouterUtils.popUntil(context, AppMain.ROUTER);
        });
  }

}